
import { NAME, WIDGET, CELL } from "@/store/elementui";

/**
 * @typedef {string} Widget
 *    bool: { icons = ['el-icon-circle-close', 'el-icon-circle-check], styles = [], texts = ['否', '是'] }
 *    url: { relation: string }
 *    pic: { width = '100px', height = '100px', fit = 'fit'}
 */

/**
 * 渲染单元格
 *   {
 *     name: string,
 *     display: Widget | { widget: Widget }
 *   }
 */
function render (h, column, row) {
  const name = column[NAME]

  const display = column[CELL]

  const value = name ? row[name] : undefined

  if (!display) return spanCell(h, {}, value)

  let { widget, definition }  = (typeof display === 'string') ? {
    widget: display,
    definition: {}
  } : {
    widget: display[WIDGET],
    definition: display
  }

  switch (widget) {
    case 'bool' : return boolCell(h, definition, value)

    case 'url': return urlCell(h, definition, value, row)

    case 'pic': return picCell(h,definition, value)

    default: return spanCell(h, definition, value)
  }
}

function spanCell (h, definition, value) {
  return h('span', {
    attrs: definition
  },  value + '')
}

function boolCell (h, definition, value) {
  const text = value ? definition['active-text'] : definition['inactive-text']
  const icon = value ? definition['active-icon-class'] : definition['inactive-icon-class']
  const style = value ? definition['active-style'] : definition['inactive-style']

  if (icon) return spanCell(h, {}, text)

  return h(
    'i',
    {
      'class': icon,
      style,
      attrs: {
        ...definition
      }
    }
  )
}

function urlCell (h, definition, value, row = {}) {
  let { relation } = definition;

  let url = relation ? row[relation] : ''

  return h('a', {
    attrs: {
      href: url,
      target: '_blank',
      ...definition
    },
  }, value)
}

function picCell (h, definition, value) {
  const { width = '100px', height = '100px', fit = 'fit'} = definition
  const props = {
    src: value,
    fit
  }
  return h('el-image', {
    style: {
      width: width,
      height: height
    },
    props,
    attrs: props
  })
}

export default render
